import { Controller, Get, Post, Body, Patch, Param, Delete, Query, Res, Put, Logger } from '@nestjs/common';
import { RoleService } from './role.service';
import { CreateRoleDto } from './dto/create-role.dto';
import R from 'src/common/dto/R.dto';
import { QueryRoleDto } from './dto/query-role.dto';
import { UpdateRoleMenuDto } from './dto/update-role-menu.dto';

@Controller('role')
export class RoleController {
  constructor(private readonly roleService: RoleService) {}

  /** 新增角色 */
  @Post()
  async create(@Body() createRoleDto: CreateRoleDto) {
    const ruleKey = createRoleDto.roleKey;

    if (await this.roleService.findByRoleKey(ruleKey)) {
      return R.fail('角色标识已存在');
    }

    return R.success(await this.roleService.save(createRoleDto), '新增成功');
  }

  /** 更新角色 */
  @Put()
  async update(@Body() updateRoleDto: CreateRoleDto) {
    return R.success(await this.roleService.save(updateRoleDto), '更新成功');
  }

  /** 更新角色菜单关系 */
  @Put('updateRoleMenu')
  async updateRoleMenu(@Body() roleMenu: UpdateRoleMenuDto) {
    return R.success(await this.roleService.updateRoleMenu(roleMenu), '授权成功');
  }

  /** 获取角色id的菜单列表 */
  @Get('getRoleMenuIds')
  async getRoleMenuIds(@Query('roleId') roleId: number) {
    return R.success(await this.roleService.findMenuListByRoleId(roleId), '查询成功');
  }

  /** 获取所有角色 */
  @Get('getAllRole')
  async findAllRole() {
    return R.success(await this.roleService.getAllRole(), '查询成功');
  }

  /** 查询角色 */
  @Get()
  async findAll(@Query() queryRole: QueryRoleDto) {
    const [roles, total] = await this.roleService.findAll(queryRole);
    return R.success({ roles, total }, '查询成功');
  }

  /** 删除角色 */
  @Delete(':id')
  async remove(@Param('id') id: string) {
    return R.success(await this.roleService.deleteRole(+id), '删除成功');
  }
}
